import React, { useEffect, useState, useCallback } from 'react';
import ReactDOM from 'react-dom';
import { isEmpty, payIcon, checkField } from '@/utils/common';
import { Mask, ModalWrap, Message  } from '@/design';
import { useSelector, useDispatch } from 'umi';

import styles from './cardPayModal.less';

// 預定信息
export default function (props: any) {
  const { modalVisiable, onClose, onClickSure } = props;
  const [cardInfo, setCardInfo] = useState<any>({});
  const { payhold } = useSelector((state: any) => state.payment);
  
  const [submitLoading, setSubmitLoading] = useState<boolean>(false);

  /* 信用卡信息 */
  const handleCardInput = (event:any, name: any) => {
    let newItem:any = {};
    newItem[name] = event.target.value;
    if (name === 'cardNo' && !isEmpty(newItem[name])) newItem[name] = newItem[name].replace(/(-)/g, '').replace(/(\d{4})/g, '$1-').replace(/-$/, '');
    setCardInfo({
      ...cardInfo,
      ...newItem
    })
  }

    /* 信用卡支付 */
    const cardSubmit = () => {
   
      let newData = JSON.parse(JSON.stringify(cardInfo));
      let msg = '';
      let nowDate = new Date();
      let nowY = String(nowDate.getFullYear()).substring(2, 4);
      let nowM = nowDate.getMonth() + 1;
      if (Number(newData['cardY']) < Number(nowY)) {
        msg = '該信用卡不在有效期內'
      } else if (Number(newData['cardM']) < Number(nowM) && Number(newData['cardY']) === Number(nowY)) {
        msg = '該信用卡不在有效期內'
      }
      if (!isEmpty(newData['cardNo'])) {
        newData['cardNo'] = newData['cardNo'].replace(/-/g, '');
      }
      // console.log(newData['cardNo'])
      msg = isEmpty(msg) ? checkField('card', newData['cardNo']) : msg;
      msg = isEmpty(msg) ? checkField('month', newData['cardM']) : msg;
      msg = isEmpty(msg) ? checkField('year', newData['cardY']) : msg;
      msg = isEmpty(msg) ? checkField('CVC', newData['cardCVC']) : msg;
      if (!isEmpty(msg)) {
        // message.info(msg , 2, null, false);
        Message.error(msg)
        return;
      }
      let vM = newData['cardM'].length === 1 ? `0${newData['cardM']}` : newData['cardM'];
      let vY = String(newData['cardY']);
      newData['cardValid'] = `${vY}${vM}`;
      delete newData['cardM'];
      delete newData['cardY'];
      console.log('提交啦', newData)
      // setShowCardPay(undefined);
      fetchOrderPay({cardData: newData })
    }

    /* 訂單支付 */
    const fetchOrderPay = async (params:any = {}) => {
      const { cardData = {} } = params;
      const { orderNo, payAmount } = props;
      const braId = localStorage.getItem('BRAID');
      const codeId = localStorage.getItem('CODEID');
      // let callBackUrl = `${window.location.origin}/payment-result/?braId=${braId}`;
      let callBackUrl = `${window.location.origin}/payment-result/?braId=${braId}&codeId=${codeId}`;

      // if (channelCode === 'linepay' || channelCode === 'gamapay') {
      setSubmitLoading(true);
      dispatch({
        type: 'payment/fetchOrderPay',
        payload: {
          orderId: orderNo,
          payWay: 'cardpay',
          payAmount,
          callBackUrl,
          payCategory: 'pay',
          ...cardData,
        }
      })
    }

    useEffect(()=> {
      if(!isEmpty(payhold)) {
        setSubmitLoading(false);
      }
    }, [payhold])

  // const { seatNum } = useSelector((state:any) => state.order);
  const dispatch = useDispatch();
  return (<ModalWrap headName={'信用卡支付'} modalVisiable={modalVisiable} onClose={onClose} noPadding={true} onClickSure={cardSubmit} submitLoading={submitLoading}>
    <div className={styles.card_pay}>
      <div className={styles.item}>
        <label>卡號</label>
        <div><input type="text" placeholder="信用卡號(格式：16-20位數字)" value={cardInfo.cardNo || ''} maxLength={24} onChange={(e:any)=>{handleCardInput(e, 'cardNo')}} /></div>
      </div>
      <div className={styles.item}>
        <label>有效期</label>
        <div><input type="text" placeholder="月(格式：MM)" maxLength={2} onChange={(e:any)=>{handleCardInput(e, 'cardM')}} /></div>
        <div><input type="text" placeholder="年(格式：YY)" maxLength={2} onChange={(e:any)=>{handleCardInput(e, 'cardY')}} /></div>
      </div>
      <div className={styles.item}>
        <label>CVC</label>
        <div><input type="text" placeholder="信用卡背面的3位安全碼" maxLength={3} onChange={(e:any)=>{handleCardInput(e, 'cardCVC')}} /></div>
      </div>
      {/* <button className={styles.submit} type="button" ga-desc="訂單支付">確認支付</button> */}
    </div>
  </ModalWrap>
  )
}